"use strict";
const tool = require("../utils/common");
const escapeInput = require("../utils/escape");
const isUserLogined = function(req, res, next) {
	console.log("检查用户登陆情况", req.session.account);
	if (req.session.account) {
		/*这是为了解决session不知道为何不会自动更新cookie.expires属性的问题，
		从debug源码后发现是因为系统在自动调用session.touch()之前就把session重新存回了db，导致更新无效
		除了需要手动调用touch()方法外，还需要将resave改为true，才能生效。*/
		req.session.touch();
		next();
	} else {
		console.error("尚未登陆");
		tool.getResponseFunc(res).fail(new Error("e_unlogin"));
	}
};
const isAdminLogined = function(req, res, next) {
	console.log("检查管理员登陆情况", req.session.account);
	if (true) {
		/*从后台查询一下此人是否admin*/
		req.session.touch();
		next();
	} else {
		console.error("admin尚未登陆");
		tool.getResponseFunc(res).fail(new Error("e_nlogin"));
	}
};

const hashSha256 = function(raw) {
	const sha256 = require("crypto").createHash("sha256");
	let result = [];
	let total = 0;

	sha256.setDefaultEncoding("utf-8");
	sha256.end(raw);
	sha256.on("data", buffer => {
		result.push(buffer);
		total += buffer.length;
	});
	return new Promise((success, fail) => {
		sha256.on("end", () => {
			const str = Buffer.concat(result, total).toString("hex");
			//console.log("读取完毕，sha256之后的数据是", str);
			success(str);
		});
		sha256.on("error", e => {
			console.error("sha256出错", e);
			fail(e);
		});
	});
};



const isFalsified = function(req, res, next) {
	if (process.env.amitabha) {
		next();
		return;
	}
	const escapeChar = function() {
		req.body = escapeInput.escapeObj(req.body);
	};
	const client = tool.getResponseFunc(res);
	const compareTo = req.get("expire-day");
	if (!compareTo) {
		console.error("没有检验头", req.originalUrl);
		client.fail(new Error("e_falsified"));
		return;
	}
	const text = Object.keys(req.body).length ?
		JSON.stringify(req.body) :
		"";
	console.log('text:'+text);
	console.log(decodeURI(req.originalUrl) + "Namo Amitabha");
	const raw = text + decodeURI(req.originalUrl) + "Namo Amitabha";

	return hashSha256(raw)
		.then(afterHash => {
			console.log(afterHash);
			console.log(compareTo);
			if (afterHash !== compareTo) {
				console.error("企图攻击？！", req.originalUrl, afterHash, compareTo);
				const e = new Error("e_falsified");
				client.fail(e);
				throw e;
			}
		})
		.then(escapeChar)
		.then(next);

};



module.exports = {
	isUserLogined,
	isFalsified,
	isAdminLogined
};